package com.wu.flandre.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wu.flandre.component.GlobalConstant;
import com.wu.flandre.dao.UserAccountDaoMapper;
import com.wu.flandre.entity.common.ResponseTemp;
import com.wu.flandre.entity.page.Login;
import com.wu.flandre.entity.table.UserAccount;
import com.wu.flandre.service.UserAccountService;
import com.wu.flandre.util.JwtUtil;
import com.wu.flandre.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wu
 * @since 2019-12-14
 */
@Service
@Slf4j
public class UserAccountServiceImpl extends ServiceImpl<UserAccountDaoMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountDaoMapper accountDaoMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public ResponseTemp userLogin(Login login) {
        ResponseTemp responseTemp = null;
        try {
            QueryWrapper<UserAccount> queryWrapper = new QueryWrapper<>();
            LambdaQueryWrapper<UserAccount> lambda = queryWrapper.lambda();
            lambda.eq(UserAccount::getUserId, login.getMail());
            lambda.eq(UserAccount::getUserPwd, login.getPassword());
            List<Map<String, Object>> userInfos = accountDaoMapper.selectMaps(lambda);
            if (userInfos.size() > 0) {
                String token = jwtUtil.generateToken(userInfos.get(0).get("UserId").toString(), GlobalConstant.AUTH_USER);
                responseTemp = ResponseUtil.success(token);
            } else {
                responseTemp = ResponseUtil.fail("登录失败");
            }
        } catch (Exception e) {
            log.error("- 用户登录Service异常:" + e.getMessage());
            responseTemp = ResponseUtil.exceptions(e.getMessage());
        }
        return responseTemp;
    }
}
